<template>
  <div class="app-container datasview">
    <el-tabs v-model="types" @tab-click="tabChange">
      <el-tab-pane label="一级分类" name="1"/>
      <el-tab-pane label="二级分类" name="2"/>
    </el-tabs>
    <div class="filter-container search">
      <tagButton :name="`新增${types==1?'一':'二'}级分类`" @click="handleadd(1)"/>
    </div>
    <!-- 查询结果 -->
    <MCTable :data-source="dataSource"/>
    <!-- 修改弹窗 -->
    <el-dialog v-if="dialogFormVisible" :visible.sync="dialogFormVisible" :title="isadd==1?'新增分类':'修改分类'" class="dialog" style="width: 100%;" close>
      <div v-show="types==2" class="item">
        <span class="title">一级分类：</span>
        <el-select v-model="updataQuery.pId" placeholder="请选择">
          <el-option
            v-for="item in cateOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </div>
      <div class="item">
        <span class="title">{{ types == 1?'一级':'二级' }}分类名称：</span>
        <el-input v-model="updataQuery.name" clearable class="" style="width: 200px;"/>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <pagination :total="total" :page.sync="page" :limit.sync="listQuery.limit" @pagination="sizeChange" />
  </div>
</template>
<script>

import BackToTop from '../../../components/BackToTop'
import Pagination from '../../../components/Pagination'
import { apiMeterial } from '../../../api/mediaManage/index'
import tagButton from '../../../components/common/tagButton'
import Fn from '../../../utils/fn'
import tableColumns from './columnsData/cateColums'
export default {
  name: 'SetCate',
  inject: ['reload'],
  components: { BackToTop, Pagination, tagButton },
  mixins: [
  ],
  data() {
    return {
      dataSource: {
        list: [],
        columns: tableColumns,
        operates: {
          fixed: 'right',
          width: '250',
          list: [
            { label: '修改', type: 'warning', show: (row) => (true),
              method: (index, row) => {
                this.handleedit(row, 2)
              }
            },
            { label: '显示', type: 'info', show: (row) => (row.hide === true),
              method: (index, row) => {
                this.handlestatus(row, 1)
              }
            },
            { label: '隐藏', type: 'info', show: (row) => (row.hide === false),
              method: (index, row) => {
                this.handlestatus(row, 1)
              }
            }
          ]
        }
      },
      cateOptions: [],
      page: 1,
      total: 0,
      isadd: 1,
      // 列表和搜索参数
      listQuery: {
        page: 1,
        limit: 20,
        level: 1
      },
      dialogFormVisible: false,
      // 素材更新的参数
      updataQuery: {
        id: undefined,
        level: undefined,
        name: undefined,
        hide: undefined,
        pId: undefined
      },
      tabs: [
        { name: '一级分类' },
        { name: '二级分类' }
      ],
      types: '1'

    }
  },
  watch: {
    types: {
      immediate: true,
      handler(n) {
        const column = {
          label: '一级分类',
          align: 'center',
          formatter: ({ pId }, column, cellValue, index) => {
            const { cateOptions } = this
            const pName = cateOptions.filter(item => item.id == pId)
            return `<span>${pName.length > 0 ? pName[0].name : ''}</span>`
          }
        }
        const temp = this.dataSource.columns[1]
        if (n === '2') {
          this.dataSource.columns.splice(1, 0, column)
        } else {
          this.dataSource.columns.splice(1, temp.label === '一级分类' ? 1 : 0)
        }
      }
    }
  },
  created() {
    this.Init()
  },
  methods: {
    // 获取关联的分类信息
    relationCategory() {
      return new Promise((resolve, reject) => {
        apiMeterial.relationCategory().then(res => {
          if (res.data.resp_code == 0) {
            this.cateOptions = res.data.datas
            resolve(res.data.datas)
          } else {
            this.toast.fail(res.data.resp_msg)
            reject(res.data)
          }
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
          reject(response)
        })
      })
    },
    sizeChange(val) {
      this.listQuery.limit = val.limit
      this.getList()
    },
    // 显示隐藏状态
    handlestatus: Fn.Confirm(function(row, type) {
      const status = !(row.hide)
      this.updataQuery.hide = status
      this.updataQuery.name = row.name
      this.updataQuery.id = row.id
      this.updataQuery.level = row.level

      apiMeterial.categoryStatus(this.updataQuery).then(res => {
        if (res.data.resp_code === 0) {
          this.toast.success('修改成功')
          this.dialogFormVisible = false
          this.getList()
        }
      }).catch(err => console.log(err))
    }),
    tabChange(tab) {
      this.page = 1
      this.getList()
    },

    // 重置页面
    refresh() {
      this.reload()
    },

    // 新增分类
    handleadd(type) {
      this.dialogFormVisible = true
      for (const key in this.updataQuery) {
        this.updataQuery[key] = undefined
      }
      this.isadd = type
    },
    // 点击修改
    handleedit(row, type) {
      this.isadd = type
      this.updataQuery.name = row.name
      this.updataQuery.id = row.id
      this.updataQuery.level = row.level
      this.updataQuery.pId = row.pId || undefined
      this.dialogFormVisible = true
    },
    // 确认修改
    updateData() {
      const { name, pId } = this.updataQuery
      if (!name || !name.trim()) return this.toast.fail('分类名称不能为空')
      this.updataQuery.name = name.trim()
      if (this.isadd == 1) {
        if (this.types == 1) {
          this.$set(this.updataQuery, 'level', 1)
        } else {
          if (!pId) return this.toast.fail('一级分类不能为空')
          this.$set(this.updataQuery, 'level', 2)
        }
        apiMeterial.addcategory(this.updataQuery).then(res => {
          if (res.data.resp_code === 0) {
            this.toast.success('添加成功')
            this.dialogFormVisible = false
            this.getList()
          }
        }).catch(err => console.log(err))
      } else {
        apiMeterial.updatecategory(this.updataQuery).then(res => {
          if (res.data.resp_code === 0) {
            this.toast.success('修改成功')
            this.dialogFormVisible = false
            this.getList()
          }
        }).catch(err => console.log(err))
      }
    },

    // 初始化页面
    Init() {
      this.getList()
      this.relationCategory()
    },
    // // 列表数据
    getList() {
      this.$set(this.dataSource, 'options', { loading: true })
      this.listQuery.page = this.page
      if (this.types == 1) {
        this.$set(this.listQuery, 'level', 1)
      } else {
        this.$set(this.listQuery, 'level', 2)
      }
      apiMeterial.categoryListpage({ ...this.listQuery }).then(res => {
        if (res.data.resp_code == 0) {
          this.dataSource.list = res.data.datas.list
          this.total = Number(res.data.datas.total)
        } else {
          this.toast.fail(res.data.resp_msg)
        }
      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
        })
      }).finally(() => {
        this.$set(this.dataSource, 'options', { loading: false })
      })
    }
  }
}
</script>

<style lang='scss' scoped>
  .datasview{
    .search{
      // display: flex;
      // align-items: center;
      .filter-item1{
        margin-left: 0px;
      }
      div{
        display: inline-block;
      }
    }
    .content{
      width:100%;
      height:auto;
      display: flex;
      justify-content: space-around;
      .left,.right{
        border:1px solid #ccc;
        // flex: 1;
        margin:0 10px;
        padding:15px;

      }
      .left{
        width:30%;
        .list{
          p{
            overflow: hidden;
            padding:10px 6px;
            & span:first-child{
              float: left;
            }
            & span:last-child{
              float: right;
            }
            // display: flex;
            // justify-content: space-around;
          }
        }
      }
      .right{
        width:60%;
        .list{
          width:100%;
          p{
            overflow: hidden;
            padding:10px 6px;
            width:100%;
            display: flex;
            justify-content: space-around;
          }
        }
      }
    }
    .dialog{
      .item{
        margin:10px 0;
        .title{
          display: inline-block;
          width:140px;
          text-align: right;
        }
      }
      .cate{
        display: flex;
        flex-wrap: wrap;
        // align-items: center;
        .cate_list{
          display: flex;
          flex-wrap: wrap;
          .list{
            display: flex;
            // flex-direction: column;
            justify-content: center;
            align-items: center;
            .select{
              width:150px;
              margin-right: 10px;
              margin-bottom: 5px;
            }
          }
        }
      }
    }
    .tabs{
        width: 90%;
        height: 30px;
        line-height: 30px;
        // margin: 15px auto;
        margin-bottom: 10px;
        padding-bottom: 15px;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #000;
        li{
            // width: 100px;
            padding:0 15px;
            text-align: center;
            font-weight:500;
            border-right: solid 2px rgba(98, 98, 98, 1);
            color: rgba(98, 98, 98, 1);
            height: 20px;
            line-height: 20px;
            cursor: pointer;

         }
         li:last-of-type{
             border: none;
         }
         li.active1{
             color: #5555FD;

         }

    }
  }
</style>
